<template>
  <PageWrapper title="网站后台管理">
    <div id="home">
      <a-card>
        <div class="flex justify-between items-center mb-4 control">
          <a-space size="middle">
            <a @click="showModal">网站控制</a>
            <a @click="showUpdatepassword">管理员密码</a>
            <a @click="openRegister">用户注册</a>
          </a-space>
          <a-space>
            <a-button type="text" @click="addAccount">创建用户</a-button>
            <a-button type="text" @click="openSoftwareprice">软件价格</a-button>
          </a-space>
        </div>
        <div class="ant-basic-table">
          <a-table class="ant-table-striped" :columns="columns" size="small" :data-source="dataSource" bordered
            :row-selection="rowSelection" :pagination="false" :scroll="{ x: 1400 }" rowKey="userId">
            <template #bodyCell="{ column, record }">
              <!-- <template v-if="column.key === 'pitchBeginDate'">
                <a-checkbox v-model:checked="startChecked"></a-checkbox>
              </template> -->
              <template v-if="column.key === 'repetition'">
                <a-checkbox v-model:checked="record.repetition" disabled></a-checkbox>
              </template>
              <!-- <template v-if="column.key === 'shortPayDate'">
                <a-checkbox
                  v-model:checked="record.shortChecked"
                  @change="changePay(record.shortChecked, record.userId, record.softwareId, 2)"
                ></a-checkbox
                >{{ record.shortPayDate }}
              </template>
              <template v-if="column.key === 'longPayDate'">
                <a-checkbox
                  v-model:checked="record.longChecked"
                  @change="changePay(record.longChecked, record.userId, record.softwareId, 1)"
                ></a-checkbox
                >{{ record.longPayDate }}
              </template> -->
              <template v-else-if="column.dataIndex === 'operation'">
                <a-popconfirm v-if="dataSource.length" title="确定删除" @confirm="onDelete(record.rowId)">
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </template>
            <template #summary>
              <a-table-summary fixed>
                <a-table-summary-row>
                  <a-table-summary-cell :index="0">合计</a-table-summary-cell>
                  <a-table-summary-cell :col-span="21"> {{ sum }} </a-table-summary-cell>
                </a-table-summary-row>
              </a-table-summary>
            </template>
          </a-table>
        </div>

        <a-row justify="space-between" class="mt-4">
          <a-col>
            <a-pagination v-model:current="pageNo" :total="totalPage" @change="changePage" />
          </a-col>

          <a-col>
            <a-space class="btn-group"><a-button @click="checkNewdata">{{ isNew ? '还原' : '查新' }}</a-button>
              <a-button @click="onAuthorize">授权</a-button>
              <a-button @click="openRentype(1)">已付款</a-button>
              <a-button @click="openRentype(2)">续租</a-button>
              <a-button type="primary" @click="onSend">发送</a-button>
            </a-space></a-col></a-row>
      </a-card>
    </div>
    <!-- 网站控制 -->
    <a-modal v-model:visible="webVisible" title="网站控制" :bodyStyle="{ padding: '24px' }">
      <template #footer>
        <a-button key="back" @click="handleCancel" :disabled="webStatus == 'offline'">暂停</a-button>
        <a-button key="submit" type="primary" @click="handleOk" :disabled="webStatus == 'online'">上线</a-button>
      </template>
      <p>网站状态：{{ webStatus == 'online' ? '上线' : '下线' }}</p>
    </a-modal>
    <!-- 管理员密码 -->
    <a-modal v-model:visible="passwordVisible" title="修改管理员密码" ok-text="提交" cancel-text="取消"
      :bodyStyle="{ padding: '24px' }" @ok="updatePassword">
      <a-form ref="passwordRef" :model="passwordState" :rules="passwordRules" :label-col="{ style: { width: '80px' } }"
        name="basic" autocomplete="off">
        <a-form-item name="account" label="账号">
          <a-input v-model:value="passwordState.account" />
        </a-form-item>
        <a-form-item name="oldPassword" label="旧密码">
          <a-input-password v-model:value="passwordState.oldPassword" />
        </a-form-item>
        <a-form-item name="newPassword" label="新密码">
          <a-input-password v-model:value="passwordState.newPassword" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 用户注册 -->
    <a-modal v-model:visible="registerVisible" title="用户注册" ok-text="提交" cancel-text="取消"
      :bodyStyle="{ padding: '24px' }" @ok="onRegister">
      <a-form ref="registerRef" :model="registerState" :rules="registerRules" :label-col="{ style: { width: '80px' } }"
        name="basic" autocomplete="off">
        <a-form-item name="account" label="账号">
          <a-input v-model:value="registerState.account" />
        </a-form-item>
        <a-form-item name="password" label="密码">
          <a-input-password v-model:value="registerState.password" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 创建用户 -->
    <a-modal v-model:visible="accountVisible" title="创建用户" ok-text="提交" cancel-text="取消" width="600px"
      :bodyStyle="{ padding: '24px' }" @ok="onOk">
      <a-form ref="accountRef" :model="accountState" :rules="accountRules" :label-col="{ style: { width: '90px' } }"
        name="basic" autocomplete="off">
        <a-row>
          <a-col :span="12">
            <a-form-item name="name" label="用户名">
              <a-input v-model:value="accountState.name" /> </a-form-item></a-col>
          <a-col :span="12">
            <a-form-item name="contact" label="联系人">
              <a-input v-model:value="accountState.contact" /> </a-form-item></a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item name="phone" label="手机">
              <a-input v-model:value="accountState.phone" maxlength="11" /> </a-form-item></a-col>
          <a-col :span="12">
            <a-form-item name="softwareName" label="软件名称">
              <a-input v-model:value="accountState.softwareName" /> </a-form-item></a-col>
        </a-row>
        <a-form-item name="address" label="地址">
          <a-textarea v-model:value="accountState.address" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 租用类型 -->
    <a-modal v-model:visible="rentVisiable" title="租用类型" :bodyStyle="{ padding: '24px' }" @ok="setRent">
      <a-radio-group v-model:value="rentType">
        <a-radio :value="1">长租</a-radio>
        <a-radio :value="2">短租</a-radio>
      </a-radio-group>
    </a-modal>
  </PageWrapper>
</template>
<script lang="ts" setup>
import { PageWrapper } from '/@/components/Page'
import type { TableProps } from 'ant-design-vue'
import { Modal, message } from 'ant-design-vue'
import { ref, reactive, onMounted } from 'vue'
import { router } from '/@/router'
import type { Rule } from 'ant-design-vue/es/form'
import {
  adminIndex,
  changeAdminPassword,
  online,
  offline,
  createUser,
  registerApi,
  checkNew,
  authorize,
  hadpay,
  renewal,
  send,
  deleteRows,
  updateUser
} from '/@/api/sys/admin'
import { getWebStatus } from '/@/api/sys/common'
const token = localStorage.getItem('TOKEN_KEY')
const rentType = ref(1)
const rentVisiable = ref(false)
const payType = ref(1)
//网站控制
const webVisible = ref<boolean>(false)
//网站状态
const webStatus = ref()
const isNew = ref(false)

async function getWeb() {
  const res = await getWebStatus()
  webStatus.value = res.data.status
}
const showModal = () => {
  getWeb()
  webVisible.value = true
}
//上线
const handleOk = async () => {
  const res = await online({ token })
  if (res.success === 1) {
    getWeb()
  } else {
    Modal.error({
      title: '错误提示',
      content: res.message,
    })
  }

  webVisible.value = false
}
//下线
const handleCancel = async () => {
  const res = await offline({ token })
  if (res.success === 1) {
    getWeb()
  } else {
    Modal.error({
      title: '错误提示',
      content: res.message,
    })
  }

  webVisible.value = false
}
//当前页码
const pageNo = ref(1)
// 总页码
const totalPage = ref(0)
//总计
const sum = ref('')

//管理员密码

interface passwordValues {
  account: string
  oldPassword: string
  newPassword: string
}
const passwordRef = ref()
const passwordVisible = ref<Boolean>(false)
const passwordState = ref<passwordValues>({
  account: '',
  oldPassword: '',
  newPassword: '',
})

const passwordRules: Record<string, Rule[]> = {
  account: [{ required: true, message: '请输入您的账号' }],
  oldPassword: [{ required: true, message: '请输入您的旧密码' }],
  newPassword: [{ required: true, message: '请输入您的新密码' }],
}
const showUpdatepassword = () => {
  passwordVisible.value = true
}
const updatePassword = () => {
  passwordRef.value
    .validateFields()
    .then(async (values: any) => {
      const res = await changeAdminPassword({
        token,
        data: values,
      })
      if (res.success === 1) {
        message.success('成功')
      } else {
        message.error(res.message)
      }
      passwordVisible.value = false
      passwordRef.value.resetFields()
    })
    .catch((info: any) => {
      console.log('Validate Failed:', info)
    })
}
//用户注册
const registerVisible = ref<boolean>(false)
const openRegister = () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    message.warning('请先选择一项数据')
    return
  }
  registerVisible.value = true
}

interface registerValues {
  account: string
  password: string
}
const registerRef = ref()

const registerState = reactive<registerValues>({
  account: '',
  password: '',
})

const registerRules: Record<string, Rule[]> = {
  account: [{ required: true, message: '请输入您的账号' }],
  password: [{ required: true, message: '请输入您的密码' }],
}

const onRegister = () => {
  console.log(registerRef.value)
  registerRef.value
    .validateFields()
    .then(async (values: any) => {
      const rows = selectedRows.value[0]
      const res = await registerApi({
        token,
        data: {
          userId: rows.userId,
          softwareId: rows.softwareId,
          account: values.account,
          password: values.password,
        },
      })
      if (res.success === 1) {
        message.success('成功')
        getTable()
      } else {
        message.error(res.message)
      }
      registerVisible.value = false
      registerRef.value.resetFields()
    })
    .catch((info: any) => {
      console.log('Validate Failed:', info)
    })
}
//创建用户
interface Values {
  name: string
  contact: string
  phone: string
  softwareName: string
  address: string
}
const accountRef = ref()
const accountVisible = ref<Boolean>(false)

const accountState = ref<Values>({
  name: '',
  contact: '',
  phone: '',
  softwareName: '',
  address: '',
})
const addAccount = () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {

  } else {
    accountState.value.name = selectedRows.value[0].userName
    accountState.value.contact = selectedRows.value[0].contact
    accountState.value.phone = selectedRows.value[0].phone
    accountState.value.softwareName = selectedRows.value[0].softwareName
    accountState.value.address = selectedRows.value[0].address

  }
  accountVisible.value = true

}
const accountRules: Record<string, Rule[]> = {
  name: [{ required: true, message: '请输入账号' }],
  phone: [{ required: true, message: '请输入手机' }],
}
const onOk = () => {
  accountRef.value
    .validateFields()
    .then(async (values: any) => {
      let res = {success:0,message:''}
      if (!selectedRows.value || selectedRows.value.length === 0) {
        res = await createUser({
          token,
          data: values,
        })
      } else {
        res = await updateUser({
          token,
          data: {...values,
            rowId:selectedRows.value[0].rowId,
            userId:selectedRows.value[0].userId
          },
        })
      }
      if (res.success === 1) {
        message.success('成功')
        getTable()
      } else {
        message.error(res.message)
      }
      accountVisible.value = false
      accountRef.value.resetFields()
    })
    .catch((info: any) => {
      console.log('Validate Failed:', info)
    })
}
//获取软件价格
function openSoftwareprice() {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    message.warning('请先选择一项数据')
    return
  }
  const rows = selectedRows.value[0]
  router.push({
    name: 'SoftwarePrice',
    query: {
      userId: rows.userId,
      // softwareId:rows.softwareId
    },
  })
}
//查新
async function checkNewdata() {
  if (!isNew.value) {
    if (!selectedRows.value || selectedRows.value.length === 0) {
      message.warning('请先选择一项数据')
      return
    }
    const res = await checkNew({ token, rowId: selectedRowKeys.value[0] })
    if (res.data.length) {
      dataSource.value = res.data
      isNew.value = true
    } else {
      Modal.success({
        title: '成功提示',
        content: '数据无重复',
      })
    }
  } else {
    getTable()
    isNew.value = false
  }


}
//授权
async function onAuthorize() {
  console.log(selectedRowKeys.value, selectedRows.value)
  if (!selectedRows.value || selectedRows.value.length === 0) {
    message.warning('请先选择一项数据')
    return
  }
  const res = await authorize({
    token,
    data: {
      id: selectedRowKeys.value[0],
    },
  })
  if (res.success === 1) {
    message.success('成功')
    getTable()
  } else {
    message.error(res.message)
  }
}
//已付款
const payParam = ref({})
function changePay(value, userId, softwareId, type) {
  console.log(value, softwareId)

  if (value) {
    payParam.value = {
      userId,
      softwareId,
      type: type,
    }
  } else {
    payParam.value = {}
  }
}
function openRentype(type) {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    message.warning('请先选择一项数据')
    return
  }
  payType.value = type
  rentVisiable.value = true
}
function setRent() {
  if (payType.value == 1) {
    onPay()
  } else {
    onRenewal()
  }
}
async function onPay() {
  const rows = selectedRows.value[0]
  const res = await hadpay({
    token,
    data: {
      userId: rows.userId,
      softwareId: rows.softwareId,
      type: rentType.value, //租用类型：1长租，2短租
    },
  })
  if (res.success === 1) {
    message.success('成功')
    getTable()
    rentVisiable.value = false
  } else {
    message.error(res.message)
  }

}
//续租
async function onRenewal() {
  const rows = selectedRows.value[0]
  const res = await renewal({
    token,
    data: {
      userId: rows.userId,
      softwareId: rows.softwareId,
      type: rentType.value, //租用类型：1长租，2短租
    },
  })
  if (res.success === 1) {
    message.success('成功')
    getTable()
    rentVisiable.value = false
  } else {
    message.error(res.message)
  }
}
//发送
async function onSend() {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    message.warning('请先选择一项数据')
    return
  }
  const rows = selectedRows.value[0]
  const res = await send({
    token,
    data: {
      ids: [rows.partnerRentRowId],
    },
  })
  if (res.success === 1) {
    message.success('成功')
    getTable()
  } else {
    message.error(res.message)
  }
}
//表格

//选中数据
interface DataType {
  userId: string
  softwareId: string
  partnerRentRowId: string
  userName: string
  contact: string
  phone: string
  address: string
  softwareName: string
  rowId:string
}
const selectedRowKeys = ref<string[]>([])
const selectedRows = ref<DataType[]>([])
const rowSelection: TableProps['rowSelection'] = {
  columnTitle: '选择',
  type: 'radio',
  columnWidth: 80,
  fixed: true,
  preserveSelectedRowKeys: true,
  onChange: (keys: string[], rows: DataType[]) => {
    selectedRowKeys.value = keys
    selectedRows.value = rows
  },
}

//表格数据
const columns = ref([
  {
    title: '序号',
    dataIndex: 'rowId',
    key: 'rowId',
    width: 50,
  },
  {
    title: '添加日期',
    dataIndex: 'addDate',
    key: 'addDate',
    width: 100,
  },
  {
    title: '合伙人姓名',
    dataIndex: 'partnerName',
    key: 'partnerName',
    width: 90,
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    width: 80,
  },
  {
    title: '联系人',
    dataIndex: 'contact',
    key: 'contact',
    width: 80,
  },
  {
    title: '手机',
    dataIndex: 'phone',
    key: 'phone',
    width: 120,
  },
  {
    title: '地址',
    dataIndex: 'address',
    key: 'address',
    width: 120,
  },
  {
    title: '账号',
    dataIndex: 'account',
    key: 'account',
    width: 80,
  },
  {
    title: '密码',
    dataIndex: 'password',
    key: 'password',
    width: 80,
  },
  {
    title: '软件名称',
    dataIndex: 'softwareName',
    key: 'softwareName',
    width: 100,
  },

  {
    title: '推销有效期',
    children: [
      {
        title: '开始日期',
        dataIndex: 'pitchBeginDate',
        key: 'pitchBeginDate',
        width: 100,
      },
      {
        title: '结束日期',
        dataIndex: 'pitchEndDate',
        key: 'pitchEndDate',
        width: 100,
      },
      {
        title: '不可推销',
        dataIndex: 'repetition',
        key: 'repetition',
        width: 80,
      },
    ],
  },
  {
    title: '租售付款',
    children: [
      {
        title: '到账日期',
        dataIndex: 'payDate',
        key: 'payDate',
        width: 100,
      },
      {
        title: '到账金额',
        dataIndex: 'payAmount',
        key: 'payAmount',
        width: 80,
      },
    ],
  },
  {
    title: '短租',
    children: [
      {
        title: '付款日期',
        dataIndex: 'shortPayDate',
        key: 'shortPayDate',
        width: 120,
      },
      {
        title: '到期日期',
        dataIndex: 'shortEndDate',
        key: 'shortEndDate',
        width: 100,
      },
    ],
  },
  {
    title: '长租',
    children: [
      {
        title: '付款日期',
        dataIndex: 'longPayDate',
        key: 'longPayDate',
        width: 120,
      },
      {
        title: '到期日期',
        dataIndex: 'longEndDate',
        key: 'longEndDate',
        width: 100,
      },
    ],
  },

  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    width: 100,
  },
  {
    title: '操作',
    fixed: 'right',
    width: 80,
    dataIndex: 'operation',
  },
])
const dataSource = ref([])
async function getTable() {
  const params = {
    token: token,
    pageNo: pageNo.value,
  }
  const res = await adminIndex(params)
  totalPage.value = res.data.totalPage
  dataSource.value = res.data.items.map((item) => {
    item.shortChecked = item.shortPayDate ? true : false
    item.longChecked = item.longPayDate ? true : false
    return item
  })
  sum.value = res.data.sum.payAmontSum
}
function changePage() {
  getTable()
}

// 页面加载时自动执行
onMounted(() => {
  getTable()
})
const startChecked = ref(false)
const nosaleChecked = ref(false)

//删除
const onDelete = async (key: string) => {
  const res = await deleteRows({
    token,
    data: { ids: [key] },
  })
  if (res.success === 1) {
    message.success('成功')
    getTable()
  } else {
    message.error(res.message)
  }
}
</script>
<style scoped lang="less">
#home {
  .control {
    a {
      color: #333;
    }
  }

  .btn-group {
    display: flex;
    justify-content: end;
  }
}
</style>
